var fs = require("fs")
var path = require("path")

var root = path.join(__dirname);
var out = '../assets/resources/base/'
// var out = './'
function readJson(d){
    var data = d;
    if(!data){
        cc.warn('没有数据啊:',data);
        return null
    }
    var str = '';
    var last = 0;
    while(true){
        var s = data.substring(0,last+1);
        var c = data.indexOf('//',last);
        var c1 = data.indexOf('/*',last);
        var m = 0
        if(c>=0){
            if(c1>=0){
                m = Math.min(c,c1);
            } else {
                m = c;
            }
        } else if(c1>=0){
            m = c1;
        } else {
            str+=data.substring(last)
            break;
        }
        if(m == c){
            var d = data.indexOf('\n',c+2);
            str+=data.substring(last,c)
            last = d+2;
        } else if(m == c1){
            var d = data.indexOf('*/',c1+2);
            str+=data.substring(last,c1)
            last = d+2;
        }
    }
    return JSON.parse(str);
}

function readDirToFile(path,tofile){
    console.log('正在打包:',path)
    let writeStream = fs.createWriteStream(tofile,{encoding:'utf8'})
    let pa = fs.readdirSync(path);
    let i=0;
    let obj = {};
    writeStream.write('module.exports = function(){\n')

    while(i<pa.length){
        let name = pa[i++];
        var info = fs.statSync(path+"/"+name)
        if(!info.isDirectory()){
            if(name.substring(name.length-3) == 'txt') {
                let content = fs.readFileSync(path+"/"+name,{encoding:'utf8'})
                content.replace(/\n/g,'');
                // obj[name.substring(0,name.length-4)] = readJson(content)+'\n'
                writeStream.write('\tthis["'+name.substring(0,name.length-4)+'"]='+content+';')
                writeStream.write('\n')
                console.log('name:',name,'已经成功')
            }
        }
    }
    // writeStream.write(JSON.stringify(obj))
    writeStream.write('}\n')
    writeStream.end();
}

console.log('root:',root)
root+='/'
try{
    readDirToFile(root+'gate',out+'base_gate.js');
    readDirToFile(root+'particle',out+'base_particle.js');
    readDirToFile(root+'path',out+'base_path.js');
    readDirToFile(root+'skill',out+'base_skillmaster.js');
    readDirToFile(root+'skill/hero',out+'base_skillhero.js');
    readDirToFile(root+'skill/boss',out+'base_skillboss.js');
    console.log('打包成功')
}catch(e){
    console.log('打包失败:',e)
}

// readDirToFile(root+args[0],root+args[1])

// readDirToFile(root+args[0],root+args[1])

// readDirToFile('D:\\Projects\\PlaneWars\\assets\\resources\\base\\skill\\hero','D:\\Projects\\PlaneWars\\assets\\resources\\base\\skill\\skillhero.txt')